package com.gewu.pm.ui.activity.home;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.TestBean;
import com.gewu.pm.ui.activity.filter.FilterMultipleActivity;
import com.gewu.pm.ui.adapter.home.CustomerVisitReportAdapter;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BasePopupWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户拜访报表
 */
public final class ReportCustomerVisitActivity extends AppActivity implements BaseAdapter.OnItemClickListener {

    private TextView tvTime;
    private RecyclerView mRecyclerView;
    private LinearLayout mFloatingItem;
    private ImageView mFloatingRankIcon;
    private TextView mFloatingRankNumber;
    private TextView mFloatingName;

    private CustomerVisitReportAdapter mAdapter;
    private List<TestBean> mDataList = new ArrayList<>();

    // 悬浮相关变量
    private boolean mIsFloatingVisible = false;
    private static final int FLOATING_THRESHOLD_DP = 60; // 60dp触发阈值
    private int mFloatingThreshold;

    public static void start(Context context) {
        Intent intent = new Intent(context, ReportCustomerVisitActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_customer_visit_report;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTime = findViewById(R.id.tv_time);
        mRecyclerView = findViewById(R.id.rv_list);
        mFloatingItem = findViewById(R.id.ll_floating_item);
        mFloatingRankIcon = findViewById(R.id.iv_floating_rank_icon);
        mFloatingRankNumber = findViewById(R.id.tv_floating_rank_number);
        mFloatingName = findViewById(R.id.tv_floating_name);

        // 计算悬浮阈值（dp转px）
        mFloatingThreshold = (int) (FLOATING_THRESHOLD_DP * getResources().getDisplayMetrics().density);

        // 设置RecyclerView
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new CustomerVisitReportAdapter(getContext());
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);

        // 设置滚动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                checkLastItemVisibility();
            }
        });

        // 设置点击事件
        setOnClickListener(tvTime, mFloatingItem);
    }

    @Override
    protected void initData() {
        loadData();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_time) {//时间选择
            List<String> str = new ArrayList<>();
            str.add("今天");
            str.add("昨天");
            str.add("本周");
            str.add("本月");
            // 获取当前显示的文本，用于设置选中状态
            String currentText = tvTime.getText().toString();
            new SelectTimePopup.Builder(getContext())
                    .setList(str)
                    .setSelectedItem(currentText)  // 根据当前显示的文本设置选中项
                    .setListener(new SelectTimePopup.OnListener() {
                        @Override
                        public void onSelected(BasePopupWindow popupWindow, String category) {
                            tvTime.setText(category);
                        }
                    })
                    .showAsDropDown(view);
        } else if (id == R.id.ll_floating_item) {
            // 悬浮项点击事件
            if (!mDataList.isEmpty()) {
                TestBean lastItem = mDataList.get(mDataList.size() - 1);
                toast(lastItem.getName());
            }
        }
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        FilterMultipleActivity.start(getActivity());//暂时跳转这里，UI上没有
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        TestBean item = mAdapter.getItem(position);
        toast(item.getName());
    }

    /**
     * 加载数据（创建测试数据）
     */
    private void loadData() {
        mDataList.clear();

        // 创建测试数据，使用id代表排序
        mDataList.add(new TestBean("1", "张三"));
        mDataList.add(new TestBean("2", "李四"));
        mDataList.add(new TestBean("3", "王五"));
        mDataList.add(new TestBean("4", "赵六"));
        mDataList.add(new TestBean("5", "钱七"));
        mDataList.add(new TestBean("6", "孙八"));
        mDataList.add(new TestBean("7", "周九"));
        mDataList.add(new TestBean("8", "吴十"));
        mDataList.add(new TestBean("9", "郑十一"));
        mDataList.add(new TestBean("10", "王十二"));
        mDataList.add(new TestBean("11", "冯十三"));
        mDataList.add(new TestBean("12", "陈十四"));
        mDataList.add(new TestBean("13", "褚十五"));
        mDataList.add(new TestBean("14", "卫十六"));
        mDataList.add(new TestBean("15", "蒋十七"));
        mDataList.add(new TestBean("100", "兰花指")); // 测试99+显示

        mAdapter.setData(mDataList);
    }

    /**
     * 检查最后一项的可见性
     */
    private void checkLastItemVisibility() {
        if (mDataList.isEmpty()) return;

        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        if (layoutManager == null) return;

        int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
        int lastItemPosition = mDataList.size() - 1;

        if (lastVisiblePosition == lastItemPosition) {
            // 最后一项可见，检查是否被底部遮挡
            View lastItemView = layoutManager.findViewByPosition(lastItemPosition);
            if (lastItemView != null) {
                int itemBottom = lastItemView.getBottom();
                int recyclerViewBottom = mRecyclerView.getBottom() - mRecyclerView.getPaddingBottom();
                int distanceFromBottom = recyclerViewBottom - itemBottom;

                if (distanceFromBottom < mFloatingThreshold) {
                    // 最后一项距离底部小于阈值，显示悬浮
                    showFloatingItem();
                } else {
                    // 最后一项距离底部大于阈值，隐藏悬浮
                    hideFloatingItem();
                }
            }
        } else if (lastVisiblePosition < lastItemPosition) {
            // 最后一项不可见（被底部遮挡），显示悬浮
            showFloatingItem();
        } else {
            // 其他情况隐藏悬浮
            hideFloatingItem();
        }
    }

    /**
     * 显示悬浮项
     */
    private void showFloatingItem() {
        if (mIsFloatingVisible || mDataList.isEmpty()) return;

        TestBean lastItem = mDataList.get(mDataList.size() - 1);

        // 设置悬浮项数据
        mFloatingName.setText(lastItem.getName());
        setupFloatingRankDisplay(mDataList.size());

        // 显示动画
        mFloatingItem.setVisibility(View.VISIBLE);
        mFloatingItem.setTranslationY(mFloatingItem.getHeight());

        ObjectAnimator animator = ObjectAnimator.ofFloat(mFloatingItem, "translationY", 0f);
        animator.setDuration(300);
        animator.start();

        mIsFloatingVisible = true;
    }

    /**
     * 隐藏悬浮项
     */
    private void hideFloatingItem() {
        if (!mIsFloatingVisible) return;

        ObjectAnimator animator = ObjectAnimator.ofFloat(mFloatingItem, "translationY", mFloatingItem.getHeight());
        animator.setDuration(300);
        animator.addListener(new android.animation.AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(android.animation.Animator animation) {
                mFloatingItem.setVisibility(View.GONE);
            }
        });
        animator.start();

        mIsFloatingVisible = false;
    }

    /**
     * 设置悬浮项排名显示
     *
     * @param rank 排名（1-based）
     */
    private void setupFloatingRankDisplay(int rank) {
        // 重置显示状态
        mFloatingRankIcon.setVisibility(View.GONE);
        mFloatingRankNumber.setVisibility(View.GONE);

        if (rank == 1) {
            // 第一名显示金冠
            mFloatingRankIcon.setImageResource(R.drawable.crown_one);
            mFloatingRankIcon.setVisibility(View.VISIBLE);
        } else if (rank == 2) {
            // 第二名显示银冠
            mFloatingRankIcon.setImageResource(R.drawable.crown_two);
            mFloatingRankIcon.setVisibility(View.VISIBLE);
        } else if (rank == 3) {
            // 第三名显示铜冠
            mFloatingRankIcon.setImageResource(R.drawable.crown_three);
            mFloatingRankIcon.setVisibility(View.VISIBLE);
        } else {
            // 其他排名显示数字圆圈
            String displayRank = rank > 99 ? "99+" : String.valueOf(rank);
            mFloatingRankNumber.setText(displayRank);
            mFloatingRankNumber.setVisibility(View.VISIBLE);
        }
    }
}
